package com.maszy.commons.tools;
/**
 * 
 */

/** 
 * @作者 Allen Shu 
 * @创建日期 2012-7-3 
 * @版本 V 1.0 
 */

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JTable;
import javax.swing.table.TableModel;

import com.maszy.bean.Dept;
import com.maszy.bean.DoorStore;
import com.maszy.bean.GoodPlan;
import com.maszy.bean.Product;
import com.maszy.service.DeptService;
import com.maszy.service.DoorStoreService;
import com.maszy.service.GoodPlanService;
import com.maszy.service.ProductService;
 
/**
 *
 * @author xiaoquan
 */
public class PrintTableTest2 implements Printable {
 
    private TableModel model = null;
    private String info;
    private int totalRow = 0;
    private static final int LEFT = 0;
    private static final int RIGHT = 1;
    private static final int CENTER = 2;
    private static final int AUTO = 3;
    private static String deptName="0";
    private static String type;
    public void printTable(TableModel model,String info,String printName) {
        this.model = model;
        this.info = info;
        totalRow = model.getRowCount();
//        PrinterJob printJob = PrinterJob.getPrinterJob();
//        printJob.setPrintable(this);
//        if (printJob.printDialog()) {
//            try {
//                printJob.print();
//            } catch (Exception ex) {
//                ex.printStackTrace();
//            }
//        }
//        String printName = "Canon MP250";
        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
		DocAttributeSet das = new HashDocAttributeSet();
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(
				flavor, das);
		for (int i = 0; i < printServices.length; i++) {
			 System.out.println("第"+(i+1)+"个打印机:"+printServices[i].getName()+"  printName:"+printName);
			if (printName.equals(printServices[i].getName())) {
				// 创建打印作业
				DocPrintJob job = printServices[i].createPrintJob();
				// 设置打印属性
				PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
				// 设置纸张大小,也可以新建MediaSize类来自定义大小
				pras.add(MediaSizeName.ISO_A4);

				// 指定打印内容
				Doc doc = new SimpleDoc(this, flavor, das);
				// 不显示打印对话框，直接进行打印工作
				try {
					job.print(doc, pras); // 进行每一页的具体打印操作
				} catch (PrintException pe) {
					pe.printStackTrace();
				}
			}
		}
    }
    private static final double paper_offset_x = 20;
    private static final double paper_offset_y = 20;
    private static final double title_time_margin = 10;
    private static final double time_body_margin = 2;
    private static final double cell_padding_y = 3;
    private static final double cell_padding_x = 2;
    private static final double body_btm_margin = 20;
    private static final double body_cell_height = 20;
    private static final Font title_font = new Font("宋体", Font.PLAIN, 18);
    private static final Font time_font = new Font("宋体", Font.PLAIN, 14);
    private static final Font body_font = new Font("宋体", Font.PLAIN, 14);
 
     
    public int print(Graphics g, PageFormat pf, int pageIndex) throws
            PrinterException {
        //纸张宽
        double pageWidth = pf.getImageableWidth();
        //纸张高
        double pageHeight = pf.getImageableHeight();
        //打印的内容起始X
        double pageStartX = pf.getImageableX();
        //打印的内容起始Y
        double pageStartY = pf.getImageableY();
 
        //表头高
        double tableHeadH = 0;
        //Cell高
        double cellH = 0;
 
        //计算表头高度和单元格高度
        g.setFont(body_font);
        FontMetrics cellFm = g.getFontMetrics();
        cellH = cellFm.getHeight() + cell_padding_y * 2 + 1;
        tableHeadH = cellH * 2;
 
        //计算Title以及其位置
        String title = info;
        g.setFont(title_font);
        FontMetrics titleFm = g.getFontMetrics();
        int titleW = titleFm.stringWidth(title);
 
        //表底和表头文字属性
        g.setFont(time_font);
        FontMetrics btmFm = g.getFontMetrics();
        FontMetrics timeFm = g.getFontMetrics();
 
        //表格以上的Margin
        double tableTopMargin = paper_offset_y + titleFm.getHeight() +
                title_time_margin + timeFm.getHeight() + time_body_margin;
 
        //表格每列的最大宽度
        double[] cellColMaxWidths = caculateTableCellWidth(model, cellFm);
 
        //当前Page的数据容量高度-不包括表头和表尾
        double currentPageDataCapacityHeight = pageHeight - tableTopMargin -
                tableHeadH - btmFm.getHeight() - body_btm_margin - 1;
 
        //当前Page的数据容量
        int currentPageBodyCapacityRows = (int) (currentPageDataCapacityHeight /
                cellH);
 
        //Y方向的分页数量
        int pagesY = 0;
        if (model.getRowCount() % currentPageBodyCapacityRows == 0) {
            pagesY = (int) (model.getRowCount() /
                    currentPageBodyCapacityRows);
        } else {
            pagesY = (int) (model.getRowCount() /
                    currentPageBodyCapacityRows) +
                    1;
        }
 
        //当前页数大于总页数时不打印
        if (pageIndex + 1 > pagesY) {
            return NO_SUCH_PAGE;
        }
 
        //绘制Title
        g.setFont(title_font);
        g.drawString(title, (int) (pageStartX +
                (pageWidth - titleW) / 2), (int) (pageStartY +
                paper_offset_y +
                titleFm.getAscent()));
 
        //绘制区域移动到新的(0,0)点
        g.translate((int) (paper_offset_x + pageStartX), (int) (tableTopMargin +
                pageStartY));
        int currentX = 0, currentY = 0;
 
        //绘制第一张表
 
        //绘制表头
        g.setFont(time_font);
        String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar
				.getInstance().getTime());
        String time = deptName+"               第"+(pageIndex + 1)+"页，共"+pagesY+"页                     "+date;
        g.drawString(time, currentX, currentY);
        currentY += 5;
        //绘制单一表头
        for (int i = 0; i < model.getColumnCount(); i++) {
            double width = cellColMaxWidths[i];
            double height = tableHeadH;
            String name = model.getColumnName(i);
            drawCell(g, name, currentX, currentY, (int) width,
                    (int) height, CENTER);
            currentX += width;
        }
 
        //绘制数据
        currentX = 0;
        currentY = (int) tableHeadH;
        //当前Page的数据容量
        int rightCellX = 0;
        int yIndex = pageIndex;
        int startRow = currentPageBodyCapacityRows * yIndex;
        int endRow = (currentPageBodyCapacityRows * (yIndex + 1)) >  //aa
                totalRow
                ? totalRow
                : (currentPageBodyCapacityRows * (yIndex + 1));
        Object a="",b="",c="";
        for (int row = startRow; row < endRow; row++) {
            //绘制单项表头下面的数据
        	a=(String)model.getValueAt(row,0);
        	b=(String)model.getValueAt(row, 1);
        	if(row-1>startRow){
        		if(!a.equals((String)model.getValueAt(row-1,0))||!b.equals((String)model.getValueAt(row-1, 1))){
        			c="f";
        		}else{
        			c="";
        		}
        	}
        	if("f".equals(c)){
      		  g.drawLine(currentX, currentY, rightCellX, currentY);
                g.drawLine(rightCellX, 5, rightCellX, currentY);
      		currentX = 0;
              currentY += cellH;
            //绘制闭合线，下面和右侧两条
        	}
            for (int i = 0; i < model.getColumnCount(); i++) {
                double width = cellColMaxWidths[i];
                double height = body_cell_height;
                Object value = model.getValueAt(row, i);
                drawCell(g, value, currentX, currentY, (int) width,
                        (int) height, AUTO);
                currentX += width;
                rightCellX = currentX;
            }
            currentX = 0;
            currentY += cellH;
        }
 
        //绘制闭合线，下面和右侧两条
        g.drawLine(currentX, currentY, rightCellX, currentY);
        g.drawLine(rightCellX, 5, rightCellX, currentY);
 
       // drawBottomInfo(pageIndex, pagesY, currentY, g, (int) pageWidth);
        return PAGE_EXISTS;
    }
 
    private void drawBottomInfo(int pageIndex, int pagesY,
            int currentY, Graphics g, int pageWidth) {
        if (pageIndex + 1 == pagesY) {
            //绘制底部信息
            int btmX = 0;
            int btmY = currentY + 20;
            g.drawString("负责人:", btmX, btmY);
            g.drawString("制表:", pageWidth / 3, btmY);
            FontMetrics fm = g.getFontMetrics();
            int dataWidth = fm.stringWidth("日期: 2009/10/26");
            g.drawString("日期:", pageWidth - dataWidth, btmY);
        }
    }
 
    /**
     * 计算最大列宽
     * @param cellFm
     * @return
     */
    private double[] caculateTableCellWidth(
            TableModel model,
            FontMetrics cellFm) {
        //表格每列的最大宽度
        double[] cellColMaxWidths = new double[model.getColumnCount()];
 
        //计算表头每列最大宽度
        double[] headerColMaxWidths = new double[model.getColumnCount()];
 
        for (int i = 0; i < model.getColumnCount(); i++) {
            String name = model.getColumnName(i);
            headerColMaxWidths[i] = cellFm.stringWidth(name) + cell_padding_x *
                    2 + 1;
        }
        //没有数据时，表头每列的最大宽度就是表格每列的最大宽度
        cellColMaxWidths = headerColMaxWidths;
        //算数据每列的最大宽度和表头每列最大宽度对比
        for (int j = 0; j < model.getRowCount(); j++) {
            for (int i = 0; i < model.getColumnCount(); i++) {
                //做些数据类型的判断
                Object value = model.getValueAt(j, i);
                if (value instanceof BigDecimal) {
                    value = ((BigDecimal) value).doubleValue();
                }
                String text = "";
                if (value != null) {
                    text = value.toString();
                }
                double temp = cellFm.stringWidth(text) + cell_padding_x * 2 + 1;
                if (cellColMaxWidths[i] < temp) {
                    cellColMaxWidths[i] = temp;
                }
            }
        }
        return cellColMaxWidths;
    }
 
    /**
     * 绘制单元格及里面的文字
     * @param g
     * @param value
     * @param x
     * @param y
     * @param width
     * @param height
     */
    private static void drawCell(Graphics g, Object value, int x, int y,
            int width,
            int height, int locate) {
 
        g.drawLine(x, y, x + width - 1, y);
        g.drawLine(x, y, x, y + height - 1);
        FontMetrics fm = g.getFontMetrics();
        if (value == null) {
            value = "";
        }
        switch (locate) {
            case 0:
                //居左
                g.drawString(value.toString(), (int) (x + cell_padding_x), y +
                        (height - fm.getHeight()) / 2 + fm.getAscent());
            case 1:
                //居右
                g.drawString(value.toString(),
                        (int) (x +
                        (width - fm.stringWidth(value.toString()) + width -
                        fm.stringWidth(value.toString()) - cell_padding_x) /
                        2), y +
                        (height - fm.getHeight()) / 2 + fm.getAscent());
            case 2:
                //居中
                g.drawString(value.toString(), x + (width - fm.stringWidth(
                        value.toString())) / 2, y + (height -
                        fm.getHeight()) / 2 + fm.getAscent());
            case 3:
                //自动判断
                NumberFormat formatter = NumberFormat.getNumberInstance();
                formatter.setMinimumFractionDigits(2);
                formatter.setMaximumFractionDigits(2);
                //根据数据类型左对齐还是右对齐绘制还是居中对齐
                if (value instanceof BigDecimal) {
                    //居右
                    value = ((BigDecimal) value).doubleValue();
                    value = formatter.format(value);
                    g.drawString(value.toString(),
                            (int) (x +
                            (width - fm.stringWidth(value.toString()) + width -
                            fm.stringWidth(value.toString()) - cell_padding_x) /
                            2), y +(height - fm.getHeight()) / 2 + fm.getAscent());
                } else if (value instanceof Integer || value instanceof Long ||
                        value instanceof Double) {
                    //居右
                    g.drawString(value.toString(),
                            (int) (x +
                            (width - fm.stringWidth(value.toString()) + width -
                            fm.stringWidth(value.toString()) - cell_padding_x) /
                            2), y +
                            (height - fm.getHeight()) / 2 + fm.getAscent());
                } else {
                    //居中
                    g.drawString(value.toString(), x + (width - fm.stringWidth(
                            value.toString())) / 2, y + (height -
                            fm.getHeight()) / 2 + fm.getAscent());
                }
        }
    }
	public void printReport2(String type) {
		// TODO Auto-generated method stub
		DeptService deptService=new DeptService();
		List<Dept> deptList=deptService.queryAll();
		if("2".equals(type)){
			this.info="下午补货单";
		}else if("3".equals(type)){
			this.info="次日补货单";
		}
		for(int q=0;q<deptList.size();q++){
				deptName=deptList.get(q).getDept_name();
				System.out.println("开始打印"+deptName+"\t"+deptList.get(q).getDept_name());
				System.out.println("------------------------------------------------------");
				PrintTableTest2 pt2=new PrintTableTest2();
				TableModel model=pt2.queryReport2(type);
				if(model!=null){
					pt2.printTable(model,this.info, deptList.get(q).getPrint_name());
				}
		}		
	}
	public static void main(String[] args) {
    	PrintTableTest2 pt=new PrintTableTest2();
    	pt.printReport2("2");
    }
	public TableModel queryReport2(String type) {
		String[] body = null;
		List<String[]> list=new ArrayList<String[]>();
			this.type = type;
			GoodPlan goodPlan = new GoodPlan();
			goodPlan.setGoodPlan_Type(type);
			if ("2".equals(type)) {
				String date = new SimpleDateFormat("yyyy-MM-dd")
						.format(Calendar.getInstance().getTime());
				goodPlan.setGoodPlan_BeginDate(date + " 04:00:00");
				goodPlan.setGoodPlan_EndDate(date + " 23:00:00");
				goodPlan.setGoodPlan_Type("2");
				goodPlan.setDept_Name(this.deptName);
				this.type = "下午补货单";
			} else if ("3".equals(type)) {
				String date = new SimpleDateFormat("yyyy-MM-dd")
						.format(Calendar.getInstance().getTime());
				String yesterday = new SimpleDateFormat("yyyy-MM-dd")
						.format(new Date(System.currentTimeMillis() - 1000 * 60
								* 60 * 24));// 获取昨天日期
				goodPlan.setGoodPlan_BeginDate(yesterday + " 00:00:00");
				goodPlan.setGoodPlan_EndDate(yesterday + " 23:59:59");
//				System.out.println(goodPlan.getGoodPlan_BeginDate()+"\t"+goodPlan.getGoodPlan_EndDate());
				goodPlan.setGoodPlan_Type("3");
				this.type = "次日补货单";
			}
			GoodPlanService goodPlanService = new GoodPlanService();
			List<GoodPlan> goodPlanList = goodPlanService
					.queryOneDayGoodPlanByDeptName(goodPlan);
			if (goodPlanList.size()>0) {
//				System.out.println("开始打印>>" + this.deptName+"\t");
				for(int j=0;j<goodPlanList.size();j++){
					System.out.print("现在是"+this.deptName+"\t"+goodPlanList.get(j).getDoorStore_Name()+"\t");
					System.out.println("共有"+goodPlanList.get(j).getProductList().size());
					if(goodPlanList.get(j).getProductList().size()>0){
						for(int k=0;k<goodPlanList.get(j).getProductList().size();k++){
							List<String> reportItemList=new ArrayList<String>();
							reportItemList.add(goodPlanList.get(j).getDoorStore_Name());
							reportItemList.add(this.deptName);
							reportItemList.add(goodPlanList.get(j).getProductList().get(k).getProduct_Name());
							reportItemList.add(goodPlanList.get(j).getProductList().get(k).getProduct_Quantity());
							reportItemList.add(goodPlanList.get(j).getProductList().get(k).getProduct_Specification());
//							reportItemList.add(goodPlanList.get(j).getProductList().get(k).getProduct_Unit());
//							System.out.print(goodPlanList.get(j).getProductList().get(k).getProduct_Name()+"\t"+goodPlanList.get(j).getProductList().get(k).getProduct_Quantity());
//							System.out.println();
//							System.out.println("------------------------------------------------------------");
							body = reportItemList.toArray(new String[reportItemList.size()]);
							for(int iii=0;iii<reportItemList.size();iii++){
									body[iii]=reportItemList.get(iii);
							}
//							for(int qqq=0;qqq<body.length;qqq++){
//								System.out.print(body[qqq]+"\t");
//							}
//							System.out.println();
							list.add((String[])body);
						}
					}
				}
			}
		if(list.size()==0){
				return null;
		}else{
			String[][] rows =new String[list.size()][body.length*2+1];
			String strb="";
			for(int iii=0,jjj=0;iii<list.size();iii++,jjj++){
				rows[jjj][5]="   ";
				strb=list.get(iii)[0];
				if(iii+2<list.size()){
					if(strb.equals(list.get(iii+1)[0])){
						rows[jjj][0]=list.get(iii)[0];
						rows[jjj][1]=list.get(iii)[1];
						rows[jjj][2]=list.get(iii)[2];
						rows[jjj][3]=list.get(iii)[3];
						rows[jjj][4]=list.get(iii)[4];
						rows[jjj][5]="   ";
						rows[jjj][6]=list.get(iii+1)[0];
						rows[jjj][7]=list.get(iii+1)[1];
						rows[jjj][8]=list.get(iii+1)[2];
						rows[jjj][9]=list.get(iii+1)[3];
						rows[jjj][10]=list.get(iii+1)[4];
						iii++;
					}else{
						rows[jjj][0]=list.get(iii)[0];
						rows[jjj][1]=list.get(iii)[1];
						rows[jjj][2]=list.get(iii)[2];
						rows[jjj][3]=list.get(iii)[3];
						rows[jjj][4]=list.get(iii)[4];
					}
				}else{
					rows[jjj][0]=list.get(iii)[0];
					rows[jjj][1]=list.get(iii)[1];
					rows[jjj][2]=list.get(iii)[2];
					rows[jjj][3]=list.get(iii)[3];
					rows[jjj][4]=list.get(iii)[4];
				}
			}
			int j=0;
			for(int i=0;i<rows.length;i++){
				if(rows[i][0]!=null){
					j++;
				}
			}
			
			String[][] new_rows=new String[j][body.length*+1];
			for(int i=0;i<new_rows.length;i++){
				new_rows[i]=rows[i];
			}
			for(int m=0;m<new_rows.length;m++){
				System.out.println(m+"-------------------------------------------------------------------------------------");
				for(int n=0;n<new_rows[m].length;n++){
					System.out.print(new_rows[m][n]+"\t");
				}
				System.out.println();
				System.out.println("-----------------------------------------------------------------------------------------");
			}
			String arr[]={"店名","部门","单品名称","数量","规格","   ","店名","部门","单品名称","数量","规格"};
			JTable table = new JTable(new_rows, arr);
			return table.getModel();
		}
	}
}

